RenderItem
<script setup>
import { VueDraggable } from 'vue-draggable-plus'
import { cloneDeep } from 'lodash-es'
import { nanoid } from 'nanoid'
import { useTemplateStore } from '@/stores'
import { provideDragKey } from '../../hooks/use-provide-key'
import RenderItem from './render-item.vue'

const { group } = inject(provideDragKey)

const schema = defineModel('schema')
const currentItem = defineModel('currentItem')

const formInstance = useTemplateRef('formInstance')

const handleSelectItem = item => {
  currentItem.value = item ?? {}
}

const removeField = index => {
  schema.value?.fieldList?.splice(index, 1)
}
const copyField = (item, index) => {
  schema.value?.fieldList?.splice(index + 1, 0, {
    ...cloneDeep(item),
    id: `${item.type}-${nanoid(4)}`,
    field: `${item.type}-${nanoid(4)}`,
  })
}

const templateStore = useTemplateStore()
watch(
  () => templateStore.currentTemplate,
  val => {
    schema.value.id = val?.value?.id ?? ''
    schema.value.name = val?.value?.name ?? ''
    schema.value.formProps = val?.value?.formProps ?? {}
    schema.value.data = val?.value?.data ?? {}
    const len = schema.value?.fieldList?.length ?? 0
    schema.value.fieldList?.splice(0, len)
    schema.value.fieldList?.push(...(val?.value?.fieldList ?? []))
  },
)

defineOptions({ name: 'FormPanel' })
</script>

<template>
  <el-form
    ref="formInstance"
    :model="schema.data"
    v-bind="schema.formProps"
    class="borderClass h-full overflow-auto"
  >
    <VueDraggable
      class="flex flex-col gap-2 p-4 w-full h-full bg-gray-500/5 rounded overflow-auto"
      v-model="schema.fieldList"
      animation="150"
      :group="group.name"
      ghostClass="ghost"
    >
      <div
        v-for="(field, fieldIndex) of schema.fieldList"
        :key="field.id"
        class="position-relative cursor-move rounded hover:bg-gray-500/10"
        :class="field === currentItem ? 'activeClass' : ''"
        @click="handleSelectItem(field)"
      >
        <RenderItem :field="field"></RenderItem>
        <div
          v-show="field === currentItem"
          class="position-absolute right-0 bottom-0"
        >
          <el-button-group size="small">
            <el-button
              icon="CopyDocument"
              type="primary"
              plain
              @click="copyField(field, fieldIndex)"
            />
            <el-button
              icon="Delete"
              type="danger"
              plain
              @click="removeField(fieldIndex)"
            />
          </el-button-group>
        </div>
      </div>
    </VueDraggable>
  </el-form>
</template>
